#include "strategies/market_making_strategy.h"
#include <spdlog/spdlog.h>
#include <algorithm>
#include <cmath>

namespace hft {

MarketMakingStrategy::MarketMakingStrategy(const std::string& name, const MarketMakingParams& params)
    : Strategy(name), params_(params) {
    last_update_time_ = std::chrono::steady_clock::now();
}

bool MarketMakingStrategy::initialize() {
    spdlog::info("Initializing market making strategy: {}", name_);
    status_ = StrategyStatus::INITIALIZED;
    return true;
}

void MarketMakingStrategy::onMarketData(const MarketDataMessage& data) {
    if (status_ != StrategyStatus::RUNNING) return;

    // 更新最新行情
    latest_quotes_[data.symbol] = data;

    // 检查是否需要更新报价
    if (shouldUpdateQuotes()) {
        updateQuotes();
        last_update_time_ = std::chrono::steady_clock::now();
    }
}

void MarketMakingStrategy::onOrderUpdate(const OrderStatus& status) {
    if (status_ != StrategyStatus::RUNNING) return;

    // 更新订单状态
    active_orders_[status.order_id] = status;

    // 如果订单被成交或取消，更新持仓
    if (status.status == OrderStatus::FILLED || status.status == OrderStatus::CANCELLED) {
        if (status.status == OrderStatus::FILLED) {
            current_position_ += (status.side == OrderSide::BUY ? 1 : -1) * status.volume;
        }
        active_orders_.erase(status.order_id);
    }
}

void MarketMakingStrategy::onTrade(const Trade& trade) {
    if (status_ != StrategyStatus::RUNNING) return;

    // 更新持仓
    current_position_ += (trade.side == OrderSide::BUY ? 1 : -1) * trade.volume;
    
    // 检查是否需要更新报价
    if (shouldUpdateQuotes()) {
        updateQuotes();
        last_update_time_ = std::chrono::steady_clock::now();
    }
}

void MarketMakingStrategy::start() {
    spdlog::info("Starting market making strategy: {}", name_);
    status_ = StrategyStatus::RUNNING;
    is_running_ = true;
    updateQuotes();
}

void MarketMakingStrategy::stop() {
    spdlog::info("Stopping market making strategy: {}", name_);
    status_ = StrategyStatus::STOPPED;
    is_running_ = false;
    cancelAllOrders();
}

void MarketMakingStrategy::pause() {
    spdlog::info("Pausing market making strategy: {}", name_);
    status_ = StrategyStatus::PAUSED;
    is_running_ = false;
    cancelAllOrders();
}

void MarketMakingStrategy::resume() {
    spdlog::info("Resuming market making strategy: {}", name_);
    status_ = StrategyStatus::RUNNING;
    is_running_ = true;
    updateQuotes();
}

void MarketMakingStrategy::updateQuotes() {
    if (latest_quotes_.empty()) {
        spdlog::warn("No market data available to update quotes");
        return;
    }

    // 批量取消现有订单
    if (!active_orders_.empty()) {
        spdlog::debug("Cancelling {} active orders", active_orders_.size());
        cancelAllOrders();
    }

    // 计算新的报价
    for (const auto& [symbol, quote] : latest_quotes_) {
        // 检查市场有效性
        if (quote.bid_price <= 0 || quote.ask_price <= 0 || quote.bid_price >= quote.ask_price) {
            spdlog::warn("Invalid market data for {}: bid={}, ask={}", 
                symbol, quote.bid_price, quote.ask_price);
            continue;
        }

        double mid_price = (quote.bid_price + quote.ask_price) / 2.0;
        double spread = calculateSpread();
        double position_penalty = calculatePositionPenalty();

        // 计算买卖价格并应用滑点保护
        double buy_price = mid_price - spread/2 - position_penalty;
        double sell_price = mid_price + spread/2 + position_penalty;
        
        // 确保报价在合理范围内
        buy_price = std::max(buy_price, quote.bid_price * 0.999);
        sell_price = std::min(sell_price, quote.ask_price * 1.001);

        // 根据持仓调整报价数量
        int buy_volume = std::min(params_.max_orders, 
            params_.max_position - current_position_);
        int sell_volume = std::min(params_.max_orders, 
            params_.max_position + current_position_);

        // 发送订单
        if (buy_volume > 0) {
            spdlog::debug("Placing buy order: price={}, volume={}", buy_price, buy_volume);
            placeOrder(buy_price, buy_volume, OrderSide::BUY);
        } else {
            spdlog::debug("Buy order skipped due to position limit");
        }

        if (sell_volume > 0) {
            spdlog::debug("Placing sell order: price={}, volume={}", sell_price, sell_volume);
            placeOrder(sell_price, sell_volume, OrderSide::SELL);
        } else {
            spdlog::debug("Sell order skipped due to position limit");
        }
    }
}

void MarketMakingStrategy::cancelAllOrders() {
    for (const auto& [order_id, status] : active_orders_) {
        if (status.status == OrderStatus::SUBMITTED || 
            status.status == OrderStatus::PARTIALLY_FILLED) {
            Order cancel_order;
            cancel_order.order_id = order_id;
            cancel_order.type = OrderType::CANCEL;
            if (order_callback_) {
                order_callback_(cancel_order);
            }
        }
    }
    active_orders_.clear();
}

void MarketMakingStrategy::placeOrder(double price, int volume, OrderSide side) {
    Order order;
    order.symbol = latest_quotes_.begin()->first;  // 使用第一个订阅的合约
    order.price = price;
    order.volume = volume;
    order.side = side;
    order.type = OrderType::LIMIT;

    if (order_callback_) {
        order_callback_(order);
    }
}

double MarketMakingStrategy::calculateSpread() const {
    if (latest_quotes_.empty()) return params_.min_spread;

    const auto& quote = latest_quotes_.begin()->second;
    double natural_spread = quote.ask_price - quote.bid_price;
    return std::max(natural_spread * params_.spread_multiplier, params_.min_spread);
}

double MarketMakingStrategy::calculatePositionPenalty() const {
    return std::abs(current_position_) * params_.position_penalty;
}

bool MarketMakingStrategy::shouldUpdateQuotes() const {
    if (!is_running_) return false;

    auto now = std::chrono::steady_clock::now();
    auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
        now - last_update_time_).count();
    
    return elapsed >= params_.order_refresh_interval;
}

} // namespace hft 